package com.zrz.service;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.zrz.dao.auto.AdminMapper;
import com.zrz.dao.auto.RecordMapper;
import com.zrz.dao.auto.RedcodeMapper;
import com.zrz.dao.auto.UserMapper;
import com.zrz.model.auto.*;
import com.zrz.resp.RecordResp;
import com.zrz.resp.VipCountResp;
import com.zrz.util.HttpRequestUtil;
import com.zrz.util.HttpUtils;
import com.zrz.util.LatitudeLontitudeUtil;
import com.zrz.util.LogUtils;
import com.zrz.vo.PositionVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RedcodeMapper redcodeMapper;
    @Value("${codeUrl}")
    private String codeUrl;
    @Value("${pageUrl}")
    private String pageUrl;

    public Admin add(Admin admin) {
        if(org.apache.commons.lang.StringUtils.isNotEmpty(admin.getMallAddress())){
            admin=getLocation(admin);
        }
        adminMapper.insertSelective(admin);
        return admin;
    }

    public Admin login(String userName, String password) {
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andUsernameEqualTo(userName);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        if (CollectionUtils.isEmpty(adminList)) {
            return null;
        }
        String md5Passworde = MD5Encode(password, "utf-8");
        if (md5Passworde.equals(adminList.get(0).getPassword())) {
            return adminList.get(0);
        }
        return null;
    }


    private static final String hexDigIts[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * MD5加密
     *
     * @param origin      字符
     * @param charsetname 编码
     * @return
     */
    private String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (null == charsetname || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception e) {
        }
        return resultString;
    }


    private String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigIts[d1] + hexDigIts[d2];
    }


    public List<PositionVO> getMallInofo(double latitude, double longitude) {
        AdminExample adminExample=new AdminExample();
        adminExample.createCriteria();
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        List<PositionVO> positionVOList = new ArrayList<>();
        for (Admin admin : adminList) {
            PositionVO positionVO = new PositionVO();
            positionVO.setLatitude(admin.getLatitude());
            positionVO.setLongitude(admin.getLongitude());
            positionVO.setId(admin.getId());
            positionVOList.add(positionVO);
        }
        return positionVOList;
    }

    public Admin getAdmin(Integer id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    public List<User> getAllUser() {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andMemberEqualTo(true);
        return userMapper.selectByExample(userExample);
    }

    public Map getRed(Integer uid, Admin admin) {
        Map map = new HashMap();
        User user = userMapper.selectByPrimaryKey(uid);
        if (user.getExtensionCount() > 0) {
            user.setExtensionCount(user.getExtensionCount() - 1);
            user.setLedExtensionCount(user.getLedExtensionCount() + 1);
            map.put("code", 0);
            map.put("msg", "领取成功");
        } else if (user.getSurplusCount() > 0) {
            user.setSurplusCount(user.getSurplusCount() - 1);
            user.setLedExtensionCount(user.getLedSurplusCount() + 1);
            map.put("code", 0);
            map.put("msg", "领取成功");
            user.setSurplusCount(user.getSurplusCount() - 1);
        } else {
            map.put("code", -1);
            map.put("msg", "没有可领数量，请推广会员！");
        }
        //插入领取记录
        Record record = new Record();
        record.setUid(uid);
        record.setBusId(admin.getId());
        record.setBusName(admin.getMallName());
        record.setNum(1);
        recordMapper.insertSelective(record);
        //更新操作
        userMapper.updateByPrimaryKeySelective(user);
        return map;

    }


    public List<Admin> getAdminList() {
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andFlagEqualTo(false);
        return adminMapper.selectByExample(adminExample);
    }

    public int pcUpdate(Admin admin) {
        return adminMapper.updateByPrimaryKeySelective(admin);
    }

    public VipCountResp getReWineCount(Admin admin, String mobile, Integer type, Integer num) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andWineCodeEqualTo(mobile).andMemberEqualTo(true);
        List<User> userList = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        }
        User user = userList.get(0);
        VipCountResp vipCountResp = new VipCountResp();
        vipCountResp.setUid(user.getId());
        vipCountResp.setNum(num);
        vipCountResp.setMallAddress(admin.getMallAddress());
        vipCountResp.setMallName(admin.getMallName());
        vipCountResp.setType(type);
        if (type == 1) {
            vipCountResp.setTitle("会员酒");
            vipCountResp.setSyCount(user.getSurplusCount());
        } else {
            vipCountResp.setTitle("推广酒");
            vipCountResp.setSyCount(user.getExtensionCount());
        }
        vipCountResp.setMallCount(admin.getTotalNum() - admin.getYsNum());
        return vipCountResp;

    }

    public List<RecordResp> getUserRecord() {
        RecordExample recordExample = new RecordExample();
        recordExample.createCriteria();
        recordExample.setOrderByClause(" get_time desc");
        List<Record> recordList = recordMapper.selectByExample(recordExample);
        List<RecordResp> recordRespList = recordList.stream().map(record -> {
            RecordResp recordResp = new RecordResp();
            User user = userService.getUserById(record.getUid());
            recordResp.setNickName(user.getNickname());
            recordResp.setRealName(user.getRealname());
            recordResp.setMobile(user.getMobile());
            recordResp.setBusName(record.getBusName());
            recordResp.setGetTime(record.getGetTime());
            recordResp.setType(record.getType());
            recordResp.setNum(record.getNum());
            return recordResp;
        }).collect(Collectors.toList());
        return recordRespList;
    }

    public String codeUrl(Admin admin){
        return codeUrl+pageUrl;
    }

    public List<Redcode> getRecodeList(){
        RedcodeExample redcodeExample=new RedcodeExample();
        redcodeExample.createCriteria();
        redcodeExample.setOrderByClause(" status ,create_time desc");
        return redcodeMapper.selectByExample(redcodeExample);
    }

    public Admin getLocation(Admin admin){
        try {
            String url = "https://restapi.amap.com/v3/geocode/geo?address=" + admin.getMallAddress() + "&key=32031f7d5a9fb8e3c39d71b97958abb2";
            String result = HttpUtils.okGet(url);
            JsonObject jsonObject = new Gson().fromJson(result, JsonObject.class);
            if (jsonObject.get("status").getAsInt() == 1) {
                JsonArray jsonArray = jsonObject.get("geocodes").getAsJsonArray();
                jsonObject=jsonArray.get(0).getAsJsonObject();
                String location = jsonObject.get("location").getAsString();
                String[] l = location.split(",");
                admin.setLatitude(Double.parseDouble(l[1]));
                admin.setLongitude(Double.parseDouble(l[0]));
            }
        }catch (Exception e){
            return admin;
        }

        return admin;
    }

}
